package com.cloudsail.domain.strategy.service.rule.chain.impl;

import cn.hutool.core.util.StrUtil;
import com.cloudsail.domain.strategy.repository.IStrategyRepository;
import com.cloudsail.domain.strategy.service.armory.IStrategyDispatch;
import com.cloudsail.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.cloudsail.domain.strategy.service.rule.chain.factor.DefaultChainFactory;
import com.cloudsail.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author CloudSailNeverSee
 * @create 2024-10-22 22:09
 * @description 权重抽奖责任链
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;
    @Resource
    protected IStrategyDispatch strategyDispatch;


    /**
     * 权重规则过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        // 1. 根据用户ID查询用户抽奖消耗的积分值，本章节我们先写死为固定的值。后续需要从数据库中查询。
        Map<Long, String> analyticalValueGroup = this.getAnalyticalValue(ruleValue);
        // 2.如果权重规则是null或空，那么也就意味着没有规则，直接交给下一个链
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            return this.next().logic(userId, strategyId);
        }
        // 3.取出Keys，并降序排序
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        analyticalSortedKeys.sort(Collections.reverseOrder());
        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);
        // 4. 找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        Long nextValue = analyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        // 5.如果真有符合的，就被规则引擎接管，开始抽奖
        if (nextValue != null) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        // 6.没有符合的正常抽，不接管
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return this.next().logic(userId, strategyId);
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        Map<Long, String> resultMap = new HashMap<>();
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        for (String ruleValueKey : ruleValueGroups) {
            // 先判空，判断权重规则是不是null
            if (StrUtil.isBlank(ruleValueKey)) return resultMap;
            String[] parts = ruleValueKey.split(Constants.COLON);
            // 若没有分成两份，那就是数据格式有误，应抛异常
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            resultMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return resultMap;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
}
